<!--业主签约对话框-->
<template>
	<a-modal v-bind="optionDialog">
		<a-form ref="form" :model="entity" layout="vertical" :rules="ownerContractRules(entity)">
			<a-typography-paragraph strong>
				<blockquote>房间信息</blockquote>
			</a-typography-paragraph>
			<a-form-item name="houseId" id="house-id" style="position: relative">
				<a-select
					:disabled="!!contract.houseId || [2].includes(contract?.signType)"
					v-model:value="entity.houseId"
					v-bind="searchOption">
					<template v-if="loadings.search" #notFoundContent>
						<a-spin spinning tip="正在搜索，请稍候……" />
					</template>
				</a-select>
			</a-form-item>
			<a-typography-paragraph strong>
				<blockquote>业主信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="6">
					<a-form-item label="姓名：" :name="['renterInfo', 'name']">
						<a-input-group compact class="display-flex">
							<a-input
								v-model:value="entity.renterInfo.name"
								@blur="entity.renterInfo.name = entity.renterInfo.name.trim()"
								:disabled="renterDisabled"
								placeholder="请输入姓名"
								style="flex: 1" />
							<a-form-item-rest>
								<a-radio-group v-model:value="entity.renterInfo.gender" button-style="solid">
									<a-radio-button :value="1">男</a-radio-button>
									<a-radio-button :value="2">女</a-radio-button>
								</a-radio-group>
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="手机号：" :name="['renterInfo', 'phone']">
						<a-input
							v-model:value.trim="entity.renterInfo.phone"
							@blur="entity.renterInfo.phone = entity.renterInfo.phone.trim()"
							:disabled="renterDisabled"
							:maxlength="11"
							placeholder="请输入手机号" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="身份信息：" :name="['renterInfo', 'identityCard']">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="entity.renterInfo.certificationType"
									:options="options.certificateTypes"
									:disabled="entity.contractMedium === 2"
									@change="form.clearValidate([['renterInfo', 'identityCard']])"
									style="width: 120px" />
							</a-form-item-rest>
							<a-input
								v-model:value.trim="entity.renterInfo.identityCard"
								:maxlength="18"
								placeholder="请输入证件号码"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="证件照片：" :name="['renterInfo', 'frontImgUrl']">
						<a-button type="primary" block @click=";(visibles.certificate = true), (renter = entity.renterInfo)">
							<template v-if="entity.renterInfo.frontImgUrl || entity.renterInfo.rearImgUrl">
								<check-outlined />
							</template>
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="业主收付款账号：" :name="['renterInfo', 'paymentNo']">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="entity.renterInfo.paymentType"
									:options="paymentAccountList"
									@change="form.clearValidate([['renterInfo', 'paymentType']])"
									placeholder="请选择类型"
									style="width: 100px" />
							</a-form-item-rest>
							<a-input
								v-model:value.trim="entity.renterInfo.paymentNo"
								placeholder="请输入账号"
								:maxlength="30"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="紧急联系人：" :name="['renterInfo', 'emergencyName']">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="entity.renterInfo.emergencyType"
									:options="relationshipList"
									placeholder="关系"
									style="width: 100px" />
							</a-form-item-rest>
							<a-input
								v-model:value="entity.renterInfo.emergencyName"
								@blur="entity.renterInfo.emergencyName = entity.renterInfo.emergencyName.trim()"
								placeholder="请输入联系人姓名"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="紧急联系人手机号：" :name="['renterInfo', 'emergencyPhone']">
						<a-input-group compact>
							<a-input
								v-model:value.trim="entity.renterInfo.emergencyPhone"
								@blur="entity.renterInfo.emergencyPhone = entity.renterInfo.emergencyPhone.trim()"
								:maxlength="11"
								placeholder="请输入联系人手机号" />
						</a-input-group>
					</a-form-item>
				</a-col>
			</a-row>
			<a-typography-paragraph strong>
				<blockquote>合同信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="5">
					<a-form-item label="成交方式/合同编号：" name="contractNo">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select v-model:value="entity.signType" disabled :options="signTypeList" style="width: 80px" />
							</a-form-item-rest>
							<a-input v-model:value.trim="entity.contractNo" placeholder="请输入合同编号" style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item name="beginTime">
						<template #label>
							<div class="display-flex">
								<span style="flex: 1">
									合同周期：
									<span class="free-rang" v-if="entity.freeDays > 0">
										(免租周期：{{ freeRange[0] }}至{{ freeRange[1] }})
									</span>
								</span>
								<span v-if="entity.beginTime && entity.endTime" style="width: 170px">{{ cycleTip }}</span>
							</div>
						</template>
						<a-input-group compact class="display-flex">
							<a-range-picker
								:value="[entity.beginTime, entity.endTime]"
								:value-format="DATE_FORMAT.DATE"
								:disabled="[[2, 3, 4].includes(contract.signType)]"
								:disabled-date="disabledDate"
								style="flex: 1"
								@change="onDateChange" />
							<a-form-item-rest>
								<a-radio-group
									class="month-quick-radio-group"
									v-model:value="entity.leasePeriod"
									button-style="solid"
									@change="quickSelectDate">
									<a-radio-button :value="12">1年</a-radio-button>
									<a-radio-button :value="24">2年</a-radio-button>
									<a-radio-button :value="36">3年</a-radio-button>
									<a-radio-button :value="60">5年</a-radio-button>
								</a-radio-group>
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="免租期天数：" name="freeDays">
						<!-- <a-input-group compact> -->
						<!-- <a-button type="primary" :disabled="subDisabled" @click="subAddfreeDaysFun('sub')">
								<template #icon><minus-outlined /></template>
							</a-button> -->
						<a-input-number
							v-model:value="entity.freeDays"
							:min="0"
							:precision="0"
							:disabled="entity.isGraded"
							:max="entity.beginTime && entity.endTime ? calculationPeriod(entity.beginTime, entity.endTime)?.daysNum : 0"
							class="rent-free-day" />
						<!-- <a-button type="primary" :disabled="addDisabled" @click="subAddfreeDaysFun('add')">
								<template #icon><plus-outlined /></template>
							</a-button> -->
						<!-- </a-input-group> -->
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="付款方式：">
						<a-input-group compact class="display-flex">
							<a-select
								v-model:value="entity.depositMonth"
								:options="mortgageMonthList.filter(e=>e.value !== 0)"
								placeholder="请选择"
								style="flex: 1" />
							<a-select v-model:value="entity.periodMonth" :options="periodMonthList" placeholder="请选择" style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="月租金：" name="price">
						<a-input-number v-model:value="entity.price" :min="0" :precision="2" placeholder="请输入租金" />
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="押金：" name="deposit">
						<a-input-number v-model:value="entity.deposit" :min="0" :precision="2" placeholder="请输入押金" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="收租日设置：" name="payPatternValue">
						<a-input-group compact class="display-flex">
							<template v-if="entity.payPattern == 1">
								<a-input-number
									v-model:value="entity.payPatternValue"
									prefix="提前"
									:min="0"
									:precision="0"
									style="flex: 1; display: flex" />
							</template>
							<template v-else>
								<a-input-number
									v-model:value="entity.payPatternValue"
									prefix="固定"
									:min="1"
									:max="31"
									:precision="0"
									style="flex: 1; display: flex" />
							</template>
							<a-form-item-rest>
								<a-select
									v-model:value="entity.payPattern"
									:options="paymentMethodList"
									style="width: 200px"
									@change="entity.payPatternValue = null" />
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="账单生成规则：">
						<a-select v-model:value="entity.cycleType" :options="moonList" placeholder="请选择账单生成规则" />
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="合同附件：">
						<a-button type="primary" block @click="visibles.attachment = true">
							<check-outlined v-if="entity.attachmentIds?.length" />
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="物业交割单：" name="delivery">
						<a-button type="primary" block :disabled="!entity.houseId" @click="visibles.delivery = true">
							<check-outlined v-if="delivery" />
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="是否分阶付款：" name="addExplanation">
						<a-select v-model:value="entity.isGraded" :options="graded" @select="isGradedChange" placeholder="请选择" />
					</a-form-item>
				</a-col>
				<template v-if="entity.isGraded">
					<a-col :span="6">
						<a-form-item label="分阶方式：">
							<a-input-group compact class="display-flex">
								<a-select v-model:value="entity.gradedType" :options="stepDown" placeholder="请选择" style="flex: 1" />
								<a-input-number v-model:value="entity.gradedNum" placeholder="请输入分阶数" :min="1" :precision="0" />
							</a-input-group>
						</a-form-item>
					</a-col>
					<a-col :span="4">
						<a-form-item label="合同分阶递增数：">
							<a-input-number v-model:value="entity.scale" :min="0" :precision="0" addon-after="%" />
						</a-form-item>
					</a-col>
					<a-col :span="4">
						<a-form-item>
							<template #label>{{}}</template>
							<a-button type="primary" block @click="generationHierarchy">生成</a-button>
						</a-form-item>
					</a-col>
				</template>
			</a-row>
			<a-form-item v-if="entity.sublevelContracts?.length" name="sublevelContracts">
				<a-form-item-rest>
					<vxe-table ref="hierarchical" :data="entity.sublevelContracts" v-bind="hierarchicalOption">
						<vxe-column min-width="200px" align="center" class-name="fee-subject-change">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								分阶周期
							</template>
							<template #default="{row, rowIndex}">
								{{ dayjs(row.beginDate).format('YYYY-MM-DD') + ' 至 ' + dayjs(row.endDate).format('YYYY-MM-DD') }}
							</template>
						</vxe-column>
						<vxe-column min-width="260px" align="center" class-name="fee-subject-change">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								分阶期限
							</template>
							<template #default="{row, rowIndex}">
								<div class="graded-box">
									<a-input-number
										:style="{width: '33%'}"
										size="small"
										:min="0"
										:precision="0"
										disabled
										v-model:value="row.year"
										@change="value => modifyStepCycle(value, row, rowIndex, 'year')"
										addon-after="年" />
									<a-input-number
										:style="{width: '33%'}"
										size="small"
										:min="0"
										:precision="0"
										disabled
										v-model:value="row.month"
										@change="value => modifyStepCycle(value, row, rowIndex, 'month')"
										addon-after="月" />
									<a-input-number
										:style="{width: '34%'}"
										size="small"
										:min="0"
										:precision="0"
										v-model:value="row.day"
										disabled
										addon-after="日" />
								</div>
							</template>
						</vxe-column>
						<vxe-column min-width="150px" align="center" class-name="fee-subject-change">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								付款方式
							</template>
							<template #default="{row, rowIndex}">
								<a-select
									v-model:value="row.periodMonth"
									:bordered="false"
									:options="periodMonthList"
									@select="periodMonthChange(rowIndex)"
									placeholder="请选择" />
							</template>
						</vxe-column>
						<vxe-column min-width="120px" align="center">
							<template #header>免租期</template>
							<template #default="{row, rowIndex}">
								<a-input-number
									v-model:value="row.freeDays"
									size="small"
									:min="0"
									:max="row.beginDate && row.endDate ? calculationPeriod(row.beginDate, row.endDate)?.daysNum : 0"
									placeholder="请输入" />
							</template>
						</vxe-column>
						<vxe-column min-width="120px" align="center" class-name="fee-subject-change">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								递增比例
							</template>
							<template #default="{row, rowIndex}">
								<a-input-number
									:disabled="rowIndex === 0"
									size="small"
									v-model:value="row.scale"
									:min="0"
									:precision="2"
									@change="scaleChange(rowIndex)"
									placeholder="请输入" />
							</template>
						</vxe-column>
						<vxe-column min-width="100px" align="center" class-name="fee-subject-change">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								月租金
							</template>
							<template #default="{row, rowIndex}">
								<a-input-number
									size="small"
									v-model:value="row.price"
									:min="0"
									:precision="2"
									@change="amountChange(rowIndex)"
									placeholder="请输入" />
							</template>
						</vxe-column>
						<!-- <vxe-column title="操作" width="60px" align="center">
							<template #default="{row, rowIndex}">
								<a
									v-color="{color: 'danger'}"
									v-if="rowIndex === entity.sublevelContracts.length - 1"
									@click="onClickToRemoveRow(rowIndex, hierarchical,1)">
									<svg-icon icon-class="trash" />
								</a>
							</template>
						</vxe-column> -->
					</vxe-table>
				</a-form-item-rest>
				<a-input disabled :bordered="false" style="position: absolute" />
			</a-form-item>
			<a-row>
				<a-col :span="24">
					<a-form-item label="补充说明：" name="addExplanation">
						<a-textarea
							v-model:value.trim="entity.addExplanation"
							placeholder="请输入补充说明"
							:rows="4"
							show-count
							:maxlength="200" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-typography-paragraph strong>
				<blockquote>
					加收费用
					<a @click="onClickToAddOtherBill">
						<plus-circle-filled />
					</a>
				</blockquote>
			</a-typography-paragraph>
			<a-form-item v-if="entity.otherExpenses?.length" name="otherExpenses">
				<a-form-item-rest>
					<vxe-table ref="otherBillTable" :data="entity.otherExpenses" v-bind="otherBillTableOption">
						<vxe-column min-width="150px" align="center" class-name="fee-subject-change">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								费用科目
							</template>
							<template #default="{row, rowIndex}">
								<a-select
									v-model:value="row.feeSubjectId"
									:disabled="row.disabled && entity.signType === 4"
									:bordered="false"
									:options="options.feeSubjects"
									@change="(value: string) => feeSubjectChange(value, row)"
									show-search
									option-filter-prop="name"
									:field-names="{label: 'name', value: 'id', options: 'metaList'}"
									placeholder="请选择费用科目" />
							</template>
						</vxe-column>
						<vxe-column min-width="150px" align="center" class-name="fee-subject-change">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								付款方式
							</template>
							<template #default="{row, rowIndex}">
								<a-select
									v-model:value="row.periodMonth"
									:disabled="row.disabled"
									:bordered="false"
									:options="periodMonthOwner"
									placeholder="请选择付款方式" />
							</template>
						</vxe-column>
						<vxe-column min-width="150px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								金额
							</template>
							<template #default="{row, rowIndex}">
								<a-input-number
									v-model:value="row.price"
									:bordered="false"
									:controls="false"
									:min="0"
									:precision="2"
									placeholder="请输入金额" />
							</template>
						</vxe-column>
						<vxe-column title="操作" width="60px" align="center">
							<template #default="{row, rowIndex}">
								<a v-color="{color: 'danger'}" @click="onClickToRemoveRow(rowIndex, otherBillTable)">
									<svg-icon icon-class="trash" />
								</a>
							</template>
						</vxe-column>
					</vxe-table>
				</a-form-item-rest>
				<a-input disabled :bordered="false" style="position: absolute" />
			</a-form-item>

			<a-typography-paragraph v-else style="margin-bottom: 2em" />
			<a-typography-paragraph strong>
				<blockquote>签约信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="8">
					<a-form-item label="签约人：" name="signEmpId">
						<dept-emp-select
							v-model:dept-id="entity.signDeptId"
							v-model:emp-id="entity.signEmpId"
							@change="form.validate('signEmpId')" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="维护人：" name="maintainerId">
						<dept-emp-select v-model:emp-id="entity.maintainerId" disabled only-dept placeholder="请选择房源" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="签约日期：" name="signTime">
						<a-date-picker v-model:value="entity.signTime" placeholder="请选择签约日期" :value-format="DATE_FORMAT.DATE" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>

		<template #footer>
			<a-button type="primary" :disabled="disables.save" :loading="loadings.save" @click="submit">保存并核对账单</a-button>
		</template>
	</a-modal>
	<!-- 附件上传 -->
	<file-upload-dialog v-model:visible="visibles.attachment" v-model:files="attachments" />
	<!-- 证件上传 -->
	<certificate-upload-dialog v-model:visible="visibles.certificate" :imgs="renter" />
	<!-- 账单预览 -->
	<bill-preview-dialog
		v-model:visible="visibles.billPreview"
		:is-resubmit="props.isResubmit || false"
		:contract="entity"
		@success="onSubmitSuccess" />
	<!-- 物业交割单 -->
	<delivery-note
		v-model:visible="visibles.delivery"
		:id="entity.housePid"
		:signType="entity.signType"
		:is-resubmit="props?.isResubmit || false"
		:contract-id="entity.contractId"
		@success="data => (delivery = XEUtils.clone(data, true))"
		:delivery="delivery" />
</template>

<script lang="ts" setup>
	import dayjs, {Dayjs} from 'dayjs'
	import {useStore} from '@/store'
	import XEUtils from 'xe-utils'
	import houseApi from '@/api/house-api'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {CheckOutlined, DownOutlined, MinusOutlined, PlusOutlined, QuestionCircleOutlined, PlusCircleFilled} from '@ant-design/icons-vue'
	import {computed, createVNode, reactive, ref, toRaw, toRef, watch, watchEffect} from 'vue'
	import {
		mortgageMonthList,
		paymentAccountList,
		paymentMethodList,
		periodMonthList,
		relationshipList,
		signTypeList,
		moonList,
		periodMonthOwner
	} from '@/utils'

	import {Img} from 'yuxin-base/src/types'
	import DATE_FORMAT, {nowDate} from 'yuxin-base/src/utils/date'
	import {DIC_LABEL_MAP} from 'yuxin-base/src/constant'
	import {VxeTableInstance, VxeTableProps} from 'vxe-table'
	import {FormInstance, Modal, message} from 'ant-design-vue'
	import {HouseDetail} from '@/interface/house'
	import {ownerContractRules} from '@/rules/contract'
	import DeliveryNote from '@/components/contract/owner-modal/sign-modal/delivery-note.vue'
	import FileUploadDialog from '@/components/common/file-upload-dialog.vue'
	import {getHouseDeliveryGetNoe, getOwnerContractDetail, getRenterPeriodTime, ownerContractSubLevel} from '@/api/contract'
	import BillPreviewDialog from '@/components/contract/owner-modal/sign-modal/bill-preview-dialog.vue'
	import CertificateUploadDialog from '@/components/common/certificate-upload-dialog.vue'
	import {defaultOwnerContract, defaultRenterInfo, OwnerContract, RenterInfo} from '@/interface/contract'
	import {CERTIFICATION_TYPE_MAP} from 'yuxin-base/src/constant/index'
	import twoColumnsSelect from '@/components/common/two-columns-select.vue'
	import fileApi from 'yuxin-base/src/api/file-api'
	import {SIGNTYPE} from '@/utils/state'

	const store = useStore()

	const props = withDefaults(
		defineProps<{
			contract?: OwnerContract
			isChooseProcedureFee?: boolean
			contractId?: string
			reset?: boolean
			//重新提交
			isResubmit?: boolean
			isConfiguration?: boolean
			visible?: boolean
		}>(),
		{
			contract: {
				// @ts-ignore成交方式【1-新签,2-续签,4重新提交】，默认新签
				signType: 1
			},
			isConfiguration: false,
			visible: false
		}
	)
	const loadings = reactive({
		save: false,
		search: false
	})

	const disables = reactive({
		save: false
	})

	const visibles = reactive({
		footer: false,
		attachment: false,
		certificate: false,
		delivery: false,
		billPreview: false,
		accessAuth: false
	})
	const optionDialog = reactive({
		width: '80vw',
		title: '业主合同',
		centered: true,
		keyboard: false,
		maskClosable: false,
		destroyOnClose: true,
		class: 'owner-sign-dialog',
		visible: toRef(props, 'visible'),
		onCancel() {
			// console.log('关闭签约对话框')
			cancel()
			emits('update:visible', false)
			setTimeout(() => emits('close'), 200)
		}
	})

	const emits = defineEmits(['update:visible', 'success', 'close'])

	// 表单内容
	const form = ref<FormInstance>()
	// 业主信息
	const renter = ref<RenterInfo>({})
	// 物业交割单
	const delivery = ref<any>()
	// 合同附件
	const attachments = ref<Img[]>([])
	// 房源信息
	const house = ref<HouseDetail>({})
	// 合同信息
	const entity = reactive<OwnerContract>(defaultOwnerContract())
	// 业主原始信息
	const originRenterInfo = ref<RenterInfo>({})
	// 免租期最大可填写
	const maxFreeNum = ref<any>(360)

	// 周期时长提示
	const cycleTip = ref<string>()

	// 业主信息禁止编辑
	const renterDisabled = computed(() => house.value.status === 20 && house.value.houseBook !== null)
	//分阶下拉
	const stepDown = [
		{
			value: 1,
			label: '按年分阶'
		},
		{
			value: 2,
			label: '按月分阶'
		}
	]
	//是否分阶
	const graded = [
		{
			value: false,
			label: '否'
		},
		{
			value: true,
			label: '是'
		}
	]

	/** 决策合同设置 */
	const contractDecision = ref<any>({
		// 紧急联系人
		emergencyName: false,
		// 物业交割单
		delivery: false,
		// 证件照片
		frontImgUrl: false,
		// 合同编号
		contractNo: false
	})

	const disabledDate = (current: Dayjs) => {
		// 续、转、换合同开始时间禁用
		if ((entity.signType || 1) > 1) {
			return current.isBefore(entity.beginTime, 'day')
		} else {
			return false
		}
	}

	watchEffect(() => {
		// 计算合同周期月数
		if (entity.beginTime && entity.endTime) {
			cycleTip.value = ''
			const beginTime = dayjs(entity.beginTime).subtract(1, 'day')
			const endTime = dayjs(entity.endTime)

			let years = endTime.diff(beginTime, 'year')
			let months = endTime.diff(beginTime, 'month')

			entity.leasePeriod = months
			if (years >= 1) {
				cycleTip.value = years + '年'
			}

			months = endTime.subtract(years, 'year').diff(beginTime, 'month')
			if (months >= 1) {
				cycleTip.value = (cycleTip.value || '') + months + '月'
			}

			const days = endTime.subtract(entity.leasePeriod, 'month').diff(beginTime, 'day')
			if (days >= 1) {
				cycleTip.value = (cycleTip.value || '') + days + '天'
			}

			if ([2].includes(props.contract?.signType)) {
				entity.freeDays = 0
			}
			if (entity.freeDays > endTime.diff(beginTime, 'day')) {
				entity.freeDays = endTime.diff(beginTime, 'day')
			}
		}
		// 附件列表
		entity.attachmentIds = attachments.value.map(o => o.id) as []
	})
	//是否分阶
	const isGradedChange = () => {
		if (entity.isGraded) {
			//分阶免租期清空
			entity.beginTime = dayjs(entity.beginTime)
				.subtract(entity.freeDays || 0, 'day')
				.format('YYYY-MM-DD')
			entity.freeDays = 0
			// entity.leasePeriod && quickSelectDate()
			subDisabled.value = true
			addDisabled.value = true
		} else {
			addDisabled.value = false
			entity.sublevelContracts = []
		}
	}
	//生成分阶
	const generationHierarchy = () => {
		if (!entity.houseId) {
			message.warn('请先选择房间')
			return
		}
		if (!entity.beginTime || !entity.endTime) {
			message.warn('请先选择合同周期')
			return
		}
		if (!entity.gradedNum) {
			message.warn('请先输入分阶数')
			return
		}
		if (entity.scale === undefined || entity.scale === null || entity.scale === '') {
			message.warn('请先输入合同分阶递增数')
			return
		}
		const dateInfo = calculationPeriod(entity.beginTime, entity.endTime)
		if (entity.gradedType === 1 && dateInfo?.yearsNum < 1) {
			message.warn('按年分阶，合同周期必须大于1年')
			return
		} else if (entity.gradedType === 2 && dateInfo?.monthNum < 1) {
			message.warn('按月分阶，合同周期必须大于1月')
			return
		} else if (entity.gradedType === 1 && entity.gradedNum > dateInfo?.yearsNum) {
			message.warn('按年分阶，分阶周期不能大于合同年限')
			return
		} else if (entity.gradedType === 2 && entity.gradedNum > dateInfo?.monthNum) {
			message.warn('按月分阶，分阶周期不能大于合同月数')
			return
		} else if (XEUtils.divide(dateInfo.monthNum, entity.gradedNum) < 1) {
			message.warn('按月分阶，分阶周期必须大于1月')
			return
		} else if (entity.price === null) {
			return message.warn('请输入租金')
		}
		getOwnerContractSubLevel()
		// addHierarchicalList(dateInfo)
	}
	const getOwnerContractSubLevel = () => {
		let monthNum = entity.gradedNum

		//按年分阶
		if (entity.gradedType === 1) {
			// 转换为月数
			monthNum = entity.gradedNum * 12
		}
		let data = {
			beginTime: entity.beginTime,
			endTime: entity.endTime,
			price: entity.price,
			periodMonth: entity.periodMonth,
			month: monthNum,
			scale: entity.scale
		}
		ownerContractSubLevel(data).then(res => {
			entity.sublevelContracts = XEUtils.clone(res.data, true)
			if (entity.sublevelContracts && entity.sublevelContracts.length) {
				for (let i = 0; i < entity.sublevelContracts?.length; i++) {
					let item = entity.sublevelContracts[i]
					if (i === 0) {
						item.scale = 0
					}
					if (item.periodMonth > 12) {
						item.periodMonth = 99
					}
					item.scale = XEUtils.toNumber(item.scale)
				}
			}
		})
	}
	//计算周期
	const calculationPeriod = (begin, end) => {
		// 计算合同周期月数
		if (begin && end) {
			let cycle = ''
			const beginTime = dayjs(begin).subtract(1, 'day')
			const endTime = dayjs(end)

			let years = endTime.diff(beginTime, 'year')
			let months = endTime.diff(beginTime, 'month')

			if (years >= 1) {
				cycle = years + '年'
			}

			months = endTime.subtract(years, 'year').diff(beginTime, 'month')
			if (months >= 1) {
				cycle = (cycle || '') + months + '月'
			}
			let days = endTime.subtract(endTime.diff(beginTime, 'month'), 'month').diff(beginTime, 'day')
			if (days >= 1) {
				cycle = (cycle || '') + days + '天'
			}
			return {
				cycle: cycle,
				years: years || 0,
				months: months || 0,
				days: days > 0 ? days : 0,
				yearsNum: endTime.diff(beginTime, 'year'),
				monthNum: endTime.diff(beginTime, 'month'),
				daysNum: endTime.diff(beginTime, 'day')
			}
		}
	}
	// 添加分阶
	const addHierarchicalList = dateInfo => {
		// 分阶数量
		let monthNum = entity.gradedNum

		//按年分阶
		if (entity.gradedType === 1) {
			// 转换为月数
			monthNum = entity.gradedNum * 12
		}

		// 总月数 / 分阶月数 = 分阶次数（向上取整）
		let splitSize = Math.ceil(dateInfo.monthNum / monthNum)

		if (dateInfo.days > 0 && dateInfo.monthNum % monthNum === 0) {
			splitSize += 1
		}
		entity.sublevelContracts = []
		// endDaysInMonth 合同月固定结束日期
		let beginDate,
			endDate,
			endDaysInMonth = parseInt(dayjs(entity.beginTime).date()) - 1
		for (let i = 0; i < splitSize; i++) {
			if (i === 0) {
				beginDate = entity.beginTime
			} else {
				beginDate = dayjs(endDate).add(1, 'day')
			}
			endDate =
				dayjs(entity.beginTime).date() === 1 ? dayjs(beginDate).add(monthNum + 1, 'month') : dayjs(beginDate).add(monthNum, 'month')
			//判断是2月，且2月天数大于28，周期开始时间大于29.结束时间不-1
			if (dayjs(endDate).month() + 1 == 2 && dayjs(beginDate).date() > 29 && dayjs(endDate).daysInMonth() > 28) {
				endDate = dayjs(endDate)
			} else if (dayjs(endDate).month() + 1 == 2 && dayjs(beginDate).date() > 28 && dayjs(endDate).daysInMonth() === 28) {
				//判断是2月，且2月天数等于于28，周期开始时间大于28，结束时间不-1
				endDate = dayjs(endDate)
			} else {
				endDate = dayjs(endDate).add(-1, 'day')
			}
			// 如果结束日期大于固定结束日期.修改结束日期
			if (dayjs(endDate).date() > endDaysInMonth) {
				endDate = dayjs(endDate).date(endDaysInMonth)
			}
			if (endDate.isAfter(entity.endTime, 'day')) {
				endDate = dayjs(entity.endTime)
			}
			if (i == splitSize - 1) {
				endDate = entity.endTime
			}
			let cycle: any = calculationPeriod(beginDate, endDate),
				periodMonth = cycle.monthNum >= entity.periodMonth ? entity.periodMonth || 1 : cycle.monthNum || 1
			if (periodMonth > 12) {
				periodMonth = 99
			}
			entity.sublevelContracts.push({
				beginDate: dayjs(beginDate).format(DATE_FORMAT.DATE),
				endDate: dayjs(endDate).format(DATE_FORMAT.DATE),
				year: cycle.years || 0,
				month: cycle.months || 0,
				day: cycle.days,
				betweenMonth: cycle.monthNum,
				//付款方式
				periodMonth: periodMonth || 1,
				//递增比例
				scale: i === 0 ? i : entity.scale,
				price:
					i === 0
						? entity.price
						: XEUtils.add(
							entity.sublevelContracts[i - 1].price,
							XEUtils.divide(XEUtils.multiply(entity.sublevelContracts[i - 1].price, i === 0 ? i : entity.scale), 100)
						)
			})
		}
	}
	//修改分阶周期
	const modifyStepCycle = (value, item, index, type) => {
		// let timeOut = setTimeout(() => {
		// endDaysInMonth 固定结束日期
		let data = calculationPeriod(item.beginDate, item.endDate),
			endDaysInMonth = parseInt(dayjs(entity.beginTime).date()) - 1
		//分阶周期小于1个月，还原原数据
		if (!item.year && !item.month && !value) {
			message.warn('分阶周期最小为1个月')
			item.year = data?.years
			item.month = data?.months
			item.day = data?.days
			return
		}
		let endDate: any = dayjs(item.beginDate)
			.add(XEUtils.add(XEUtils.multiply(item.year, 12), item.month), 'month')
			.format(DATE_FORMAT.DATE)
		//判断是2月，且2月天数大于28，周期开始时间大于29.结束时间不-1
		if (dayjs(item.endDate).month() + 1 == 2 && dayjs(item.beginDate).date() > 29 && dayjs(item.endDate).daysInMonth() > 28) {
			endDate = dayjs(item.endDate).format(DATE_FORMAT.DATE)
		} else if (dayjs(endDate).month() + 1 == 2 && dayjs(item.beginDate).date() > 28 && dayjs(item.endDate).daysInMonth() === 28) {
			//判断是2月，且2月天数等于于28，周期开始时间大于28，结束时间不-1
			endDate = dayjs(endDate).format(DATE_FORMAT.DATE)
		} else {
			endDate = dayjs(item.beginDate)
				.add(XEUtils.add(XEUtils.multiply(item.year, 12), item.month), 'month')
				.subtract(1, 'day')
				.format(DATE_FORMAT.DATE)
		}

		//结束时间>合同结束时间 = 合同结束时间
		item.endDate = new Date(endDate).getTime() > new Date(entity.endTime || nowDate()).getTime() ? entity.endTime : endDate
		//结束日期不等于合同结束日期，固定结束日期
		if (
			new Date(item.endDate).getTime() !== new Date(entity.endTime || nowDate()).getTime() &&
			dayjs(item.endDate).date() > endDaysInMonth
		) {
			item.endDate = dayjs(endDate).date(endDaysInMonth).format(DATE_FORMAT.DATE)
		}

		let dataInfo = calculationPeriod(item.beginDate, item.endDate)
		item.year = dataInfo?.years
		item.month = dataInfo?.months
		item.day = dataInfo?.days
		item.betweenMonth = dataInfo?.monthNum
		//付款方式= 分阶月数<选择的分阶数
		item.periodMonth = dataInfo && dataInfo?.monthNum < parseInt(entity.periodMonth) ? dataInfo?.monthNum || 1 : item.periodMonth || 1
		if (item.periodMonth > 12) {
			item.periodMonth = 99
		}
		let sublevelContracts: any = XEUtils.clone(entity.sublevelContracts as [], true)
		if (new Date(item.endDate).getTime() >= new Date(entity.endTime || nowDate()).getTime() && dataInfo) {
			//结束时间>=合同结束时间,删除后面的分阶
			index !== sublevelContracts.length - 1 && sublevelContracts.splice(index + 1, sublevelContracts.length - 1)
		} else if (
			index !== sublevelContracts.length - 1 &&
			new Date(item.endDate).getTime() < new Date(entity.endTime || nowDate()).getTime()
		) {
			//分阶周期不是最后一个，改动后一个的分阶时间
			sublevelContracts[index + 1].beginDate = dayjs(item.endDate).add(1, 'day').format(DATE_FORMAT.DATE)
			let dataLastInfo = calculationPeriod(sublevelContracts[index + 1].beginDate, sublevelContracts[index + 1].endDate)
			//如果分阶时间修改超过下一个周期，直接跳到下一个周期
			if (dataLastInfo?.daysNum <= 0) {
				sublevelContracts[index + 2].beginDate = dayjs(item.endDate).add(1, 'day').format(DATE_FORMAT.DATE)
				sublevelContracts.splice(index + 1, 1)
			} else {
				//否则修改下一个周期的值
				sublevelContracts[index + 1].year = dataLastInfo?.years
				sublevelContracts[index + 1].month = dataLastInfo?.months
				sublevelContracts[index + 1].day = dataLastInfo?.days
				sublevelContracts[index + 1].betweenMonth = dataLastInfo?.monthNum
				sublevelContracts[index + 1].periodMonth =
					dataLastInfo && dataLastInfo.monthNum < parseInt(sublevelContracts[index + 1].periodMonth)
						? dataLastInfo?.monthNum || 1
						: sublevelContracts[index + 1].periodMonth || 1
				if (sublevelContracts[index + 1].periodMonth > 12) {
					sublevelContracts[index + 1].periodMonth = 99
				}
			}
		} else if (
			index === sublevelContracts?.length - 1 &&
			new Date(item.endDate).getTime() < new Date(entity.endTime || nowDate()).getTime()
		) {
			//分阶周期是最后一个，分阶时间不等于合同结束时间，自动生成一个分阶周期
			let beginTime = dayjs(item.endDate).add(1, 'day').format(DATE_FORMAT.DATE),
				endTime = entity.endTime,
				cycle: any = calculationPeriod(beginTime, endTime),
				periodMonth = entity.periodMonth || 1
			if ((cycle.yearsNum * 12 + cycle.monthNum) % entity.gradedNum < entity.periodMonth) {
				periodMonth = (cycle.yearsNum * 12 + cycle.monthNum) % entity.gradedNum || 1
			}
			if (periodMonth > 12) {
				periodMonth = 99
			}
			sublevelContracts.push({
				id: beginTime + endTime + sublevelContracts.length,
				beginDate: beginTime,
				endDate: endTime,
				year: cycle.years,
				month: cycle.months,
				day: cycle.days,
				betweenMonth: cycle.monthNum,
				//付款方式
				periodMonth: periodMonth || 1,
				freeDays: null,
				//递增比例
				scale: entity.scale,
				//先乘除，后加减 分阶租金
				price: XEUtils.add(item.price, XEUtils.divide(XEUtils.multiply(item.price, item.scale), 100))
			})
		}
		// sublevelContracts[index] = Object.assign({}, item)
		entity.sublevelContracts = XEUtils.clone(sublevelContracts as [], true)
		// 	clearTimeout(timeOut)
		// }, 500)
		// otherBillTable.value?.reloadData(sublevelContracts)
	}

	//递增比例
	const scaleChange = index => {
		let sublevelContracts: any = XEUtils.clone(entity.sublevelContracts as [], true)
		//计算当前行价格
		sublevelContracts[index].price = XEUtils.add(
			sublevelContracts[index - 1].price || sublevelContracts[index - 1].price,
			XEUtils.divide(XEUtils.multiply(sublevelContracts[index - 1].price, sublevelContracts[index].scale), 100)
		)
		//计算后面所有行价格
		if (index !== sublevelContracts.length - 1) {
			for (let i = index; i < sublevelContracts.length; i++) {
				sublevelContracts[i].price = XEUtils.add(
					sublevelContracts[i - 1].price,
					XEUtils.divide(XEUtils.multiply(sublevelContracts[i - 1].price, sublevelContracts[i].scale), 100)
				)
			}
		}
		entity.sublevelContracts = XEUtils.clone(sublevelContracts as [], true)
	}
	//月租金
	const amountChange = index => {
		if (index !== 0 && entity.sublevelContracts[index].price < entity.sublevelContracts[index - 1].price) {
			entity.sublevelContracts[index].price = entity.sublevelContracts[index - 1].price
		}
		let sublevelContracts: any = XEUtils.clone(entity.sublevelContracts as [], true)
		if (index !== 0 && sublevelContracts) {
			//计算当前递增比例，先减后除再*100
			sublevelContracts[index].scale = XEUtils.multiply(
				XEUtils.divide(
					XEUtils.subtract(sublevelContracts[index]?.price, sublevelContracts[index - 1]?.price),
					sublevelContracts[index - 1]?.price
				),
				100
			).toFixed(2)
		}
		//计算后面所有行价格
		if (sublevelContracts && index !== sublevelContracts.length - 1) {
			for (let i = index + 1; i < sublevelContracts.length; i++) {
				sublevelContracts[i].price = XEUtils.add(
					sublevelContracts[i - 1].price,
					XEUtils.divide(XEUtils.multiply(sublevelContracts[i - 1].price, sublevelContracts[i].scale), 100)
				)
			}
		}
		entity.sublevelContracts = XEUtils.clone(sublevelContracts as [], true)
	}
	//付款方式
	const periodMonthChange = index => {
		if (entity.sublevelContracts && entity.sublevelContracts.length) {
			let info: any = entity.sublevelContracts[index] || {}
			let itemDate: any = calculationPeriod(info.beginDate, info.endDate)
			info.periodMonth = itemDate?.monthNum < info.periodMonth ? itemDate?.monthNum || 1 : info.periodMonth || 1
			if (info.periodMonth > 12) {
				info.periodMonth = 99
			}
		}
	}

	// 计算押金
	watch([() => entity.price, () => entity.depositMonth], (newVal, oldVal) => {
		entity.deposit = XEUtils.multiply(entity.price, entity.depositMonth)
		//租金变化，重新更新分阶列表租金
		if (newVal[0] !== oldVal[0] && entity.sublevelContracts && entity.sublevelContracts.length) {
			entity.sublevelContracts[0].price = entity.price
			amountChange(0)
		}
	})
	// 加减免租期
	const subAddfreeDaysFun = (type: any) => {
		if (type === 'add') {
			if (!entity.beginTime) {
				message.warn('请先选择合同周期')
				return
			}
			if (maxFreeNum.value > entity.freeDays) {
				entity.freeDays++
			}
		} else {
			if (entity.freeDays > 0) {
				entity.freeDays--
			}
		}
		blurFreeDay(type)
	}

	// 监听加减免租期是否可点
	const subDisabled = ref<boolean>(true)
	const addDisabled = ref<boolean>(true)
	watch([() => entity.freeDays, () => maxFreeNum.value], () => {
		if (!entity.isGraded) {
			if (entity.freeDays <= 0) {
				subDisabled.value = true
			} else {
				subDisabled.value = false
			}
			if (entity.freeDays >= maxFreeNum.value && entity.freeDays !== 0) {
				addDisabled.value = true
			} else {
				addDisabled.value = false
			}
		}
	})

	// 计算免租周期
	const freeRange = ref<any>([])

	const blurFreeDay = (type: any) => {
		if (props.contract?.signType === 1) {
			//新签
			if (type === 'add') {
				entity.beginTime = dayjs(entity.beginTime).add(1, 'day').format(DATE_FORMAT.DATE)
				entity.endTime = dayjs(entity.endTime).add(1, 'day').format(DATE_FORMAT.DATE)
			} else {
				entity.beginTime = dayjs(entity.beginTime).subtract(1, 'day').format(DATE_FORMAT.DATE)
				entity.endTime = dayjs(entity.endTime).subtract(1, 'day').format(DATE_FORMAT.DATE)
			}
		}
	}
	watch([() => entity.freeDays, () => entity.beginTime], () => {
		// freeRange.value[0] = dayjs(entity.beginTime)
		// 	.subtract(entity.freeDays || 0, 'day')
		// 	.format('YYYY-MM-DD')
		// freeRange.value[1] = dayjs(entity.beginTime).subtract(1, 'day').format('YYYY-MM-DD')
		freeRange.value[0] = entity.beginTime
		freeRange.value[1] = dayjs(entity.beginTime).add(entity.freeDays, 'day').add(-1, 'day').format('YYYY-MM-DD')
		if (dayjs(freeRange.value[1]).isAfter(entity.endTime)) {
			freeRange.value[1] = entity.endTime
		}
	})

	const init = async () => {
		getDics()
		entity.resubmit = props?.isResubmit || false
		entity.reset = props?.reset || false
		const contract: OwnerContract = props.contract || ({} as OwnerContract)

		let renterInfo = contract.renterInfo || {}

		if (contract.otherExpenses && XEUtils.isString(contract.otherExpenses)) {
			try {
				contract.otherExpenses = JSON.parse(contract.otherExpenses || '[]')
			} catch (e) {
				contract.otherExpenses = []
			}
		}

		// @ts-ignore，过滤掉空值
		renterInfo = XEUtils.pick(renterInfo, v => v)
		originRenterInfo.value = renterInfo

		delete contract.renterInfo

		if (XEUtils.isString(renterInfo.interest) && XEUtils.trim(renterInfo.interest)) {
			renterInfo.interest = renterInfo.interest.split('/')
		}

		XEUtils.merge(entity, defaultOwnerContract(), contract, {
			renterInfo,
			contractId: null,
			contractNo: null,
			signEmpId: store.currentUser.empId,
			signDeptId: store.currentUser.deptId,
			contractDecision: contractDecision,
			signTime: nowDate()
		})

		// TODO: 调试用
		// getContractDetail('1651873159461814274')
		// 续租、合同重置、重新提交需要传contractId
		if (props.contractId) {
			getContractDetail(props.contractId)
			getDeliveryGetNoe(props.contractId)
		} else if (contract.houseId || props.contract?.houseId) {
			getHouseRoom(contract?.houseId || props.contract?.houseId)
		}

		if (props.contract?.signType === 1 || entity.signType === 1) {
			maxFreeNum.value = dayjs(entity.endTime).diff(dayjs(entity.beginTime), 'day')
			addDisabled.value = false
		}
	}

	// 获取合同详情
	const getContractDetail = (id: string) => {
		getOwnerContractDetail(id).then(({data}: {data: OwnerContract}) => {
			const renterInfo = data.renterInfo || {}

			const signType = props.contract?.signType || 1

			if (XEUtils.isString(renterInfo.interest) && XEUtils.trim(renterInfo.interest)) {
				renterInfo.interest = renterInfo.interest.split('/')
			}

			if (data.otherExpenses && XEUtils.isString(data.otherExpenses)) {
				try {
					data.otherExpenses = JSON.parse(data.otherExpenses || '[]')
				} catch (e) {
					data.otherExpenses = []
				}
			}

			if (signType > SIGNTYPE.NEWSIGNING && !entity.reset && !entity.resubmit) {
				data.contractId = null
				data.contractPid = id
				data.signType = signType
				data.signTime = nowDate()
				data.contractNo = null
				data.addExplanation = null
				switch (signType) {
					case 2:
						// 续签周期计算

						data.beginTime = dayjs(data.endTime).add(1, 'day').format(DATE_FORMAT.DATE)
						if (props.contract?.endTime && props.contract?.applyId) {
							data.endTime = props.contract.endTime
						} else {
							data.endTime = dayjs(data.beginTime).add(5, 'year').subtract(1, 'day').format(DATE_FORMAT.DATE)
						}
						break
					case 4:
						// 换房删除原房源id
						data.houseId = null
						// 换房周期计算，开始日期为操作日期第二天
						data.beginTime = dayjs(nowDate()).add(1, 'day').format(DATE_FORMAT.DATE)
						break
				}
			} else {
				// 签约申请、合同重置、重新提交合同ID不变
				entity.contractId = id
			}

			// @ts-ignore
			data = XEUtils.pick(data, v => v)
			// @ts-ignore
			data.renterInfo = XEUtils.pick(renterInfo, v => v)

			XEUtils.merge(entity, data)
			if (props.contractId && (props.isResubmit || props.reset)) {
				entity.price = data?.price || null
				entity.deposit = data?.deposit || null
				entity.sublevelContracts = []
				entity.isGraded = entity?.sublevelContracts.length ? true : false
			} else if (props.contractId) {
				entity.sublevelContracts = []
			}
			delete entity.house
			console.log('合同详情==============>', toRaw(data))

			getHouseRoom(entity.houseId as string)
		})
	}

	// 获取物业交割单
	const getDeliveryGetNoe = (contractId: string) => {
		if (entity.resubmit || props?.isResubmit || props?.reset) {
			const params = {
				id: contractId,
				type: 1
			}

			Promise.all([getHouseDeliveryGetNoe(params), fileApi.getFileList(contractId)])
				.then(([{data: deliveryData}, {data: data}]) => {
					delivery.value = deliveryData
					attachments.value = data.map(o => {
						o.name = o.fileOriginName
						return o
					})
				})
				.catch(error => {
					console.error(error)
				})
		}
	}

	// 房源搜索
	const searchOption = reactive<any>({
		options: [],
		allowClear: true,
		showSearch: true,
		optionFilterProp: 'address',
		placeholder: '请输入房源地址进行搜索',
		fieldNames: {label: 'address', value: 'houseRoomId'},
		style: {
			width: '100%'
		},
		onSearch(like: string) {
			if (like && like.trim()) {
				houseSearch(like)
			}
		},
		onSelect(value: string) {
			getHouseRoom(value)
			entity.sublevelContracts = []
			form.value?.clearValidate()
			// getConfigurationF(value)
		},
		onDeselect() {
			entity.contractMedium = 1
			entity.econtractModelId = null
		},
		getPopupContainer(triggerNode: HTMLDivElement) {
			return triggerNode ? triggerNode.parentNode : document.body
		}
	})

	const houseSearch = XEUtils.debounce((like: string) => {
		let params = {
			houseType: 0,
			like,
			current: 1,
			bizType: 2,
			size: 20,
			houseBizMode: 1
		}

		loadings.search = true
		houseApi
			.searchByAddress(params)
			.then((res: any) => {
				searchOption.options = res.data.records
			})
			.finally(() => (loadings.search = false))
	}, 300)

	// 当前签约房源
	const getHouseRoom = (id: string) => {
		entity.houseId = id
		houseApi.getHouseRoom(id).then(({data}: {data: HouseDetail}) => {
			console.log('房源详情==============>', toRaw(data))
			//用于物业交割单查询固定资产
			entity.housePid = data.housePid
			disables.save = false
			// if (data.houseBook && data.houseBook.bookStatus === 1) {
			// 	disables.save = true
			// 	house.value = {}
			// 	XEUtils.assign(entity, defaultOwnerContract())
			// 	entity.houseAddress = data.address
			// 	return Modal.warning({
			// 		centered: true,
			// 		title: '系统提示',
			// 		content: '当前房源存在预定未支付记录，请先完成支付或作废后再进行签约'
			// 	})
			// } else {
			// 	disables.save = false
			// }
			entity.signType === 1 && renterPeriodTime()
			house.value = data
			entity.isFirst = 0
			if (!(props.contractId && (props.isResubmit || props.reset))) {
				entity.price = data.houseBase?.costPrice || null
				entity.basePrice = data.houseBase?.costPrice || null
			}
			entity.houseType = data.houseType
			entity.housePid = data.housePid
			entity.houseAddress = data.address
			entity.maintainerId = data.stewardId
			const signType = props.contract?.signType || 1

			// 有id代表是签约申请转签约、合同重置
			if (signType === 1 && !entity.id) {
				entity.leasePeriod = 60

				if (data.houseBookId && data.houseBook) {
					entity.renterInfo = defaultRenterInfo()

					const houseBook = data.houseBook
					entity.renterInfo.name = houseBook.name
					entity.renterInfo.phone = houseBook.phone
					entity.renterInfo.gender = houseBook.gender || 1
					entity.leasePeriod = houseBook.contractMonth
					entity.renterInfo.identityCard = houseBook.certificateNo
					entity.renterInfo.certificationType = houseBook.certificateType || 1

					quickSelectDate()
				}
			}

			if (searchOption.options.length === 0) {
				searchOption.options = [
					{
						housePid: entity.housePid,
						houseRoomId: entity.houseId,
						address: entity.houseAddress
					}
				]
			}
		})
	}

	const options = reactive<any>({
		// 费用科目
		feeSubjects: [],
		// 证件类型
		certificateTypes: Object.keys(CERTIFICATION_TYPE_MAP).map(key => ({
			label: CERTIFICATION_TYPE_MAP[key],
			value: Number(key)
		}))
	})

	// 获取字典
	const getDics = () => {
		// 新签查询全部
		settingApi
			.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT'], {isUse: props.contractId ? null : 1})
			.then(({data}) => (options.feeSubjects = data))
	}
	// 分阶列表
	const hierarchical = ref<VxeTableInstance>()
	const hierarchicalOption = reactive<VxeTableProps>({
		size: 'mini',
		maxHeight: 200,
		border: true,
		cellStyle: {padding: 0},
		rowClassName: 'edit-table-row',
		rowConfig: {
			useKey: true,
			keyField: 'id'
		}
	})

	// 其它费用
	const otherBillTable = ref<VxeTableInstance>()
	const otherBillTableOption = reactive<VxeTableProps>({
		size: 'mini',
		maxHeight: 200,
		border: true,
		cellStyle: {padding: 0},
		rowClassName: 'edit-table-row'
	})

	// 添加其它费用
	const onClickToAddOtherBill = () => {
		entity.otherExpenses?.push({})

		otherBillTable.value?.reloadData(entity.otherExpenses as [])
	}
	/** 换房手续费 转租手续费 */
	const targetFeeTagList = ['EXCHANGE_PROCEDURE_FEE', 'SUBLEASE_PROCEDURE_FEE']
	/** 加收费用 费用科目 change事件 */
	const feeSubjectChange = (value: string, row: any) => {
		let target: any = {}
		let tag = ''
		options.feeSubjects.forEach(item => {
			const obj = item.metaList.find(v => v.id === value)
			if (obj) {
				target = item
				tag = obj.tag
			}
		})
		if (target.label === 'FEESUBJECT@DEPOSIT') {
			// 付款方式 为 一次性付清 且 不可以修改
			row.periodMonth = 99
			row.disabled = true
		} else if (target.label === 'FEESUBJECT@PROCEDURE' && targetFeeTagList.includes(tag)) {
			// 手续大类  && entity.signType === 4
			row.periodMonth = 99
			row.disabled = true
		} else {
			row.disabled = false
			if (row.periodMonth === 99) {
				delete row.periodMonth
			}
		}
	}

	// 需要被禁用的费用科目大类集合
	// const targetFeeDisabledList = ['FEESUBJECT@DEPOSIT', 'FEESUBJECT@PROCEDURE']
	// 判断是否 押金大类 手续费大类
	const isFeeSubject = (list: any[], tId: string) => {
		let res = false
		list.forEach(item => {
			if (item.label === 'FEESUBJECT@DEPOSIT') {
				res = Boolean(item.metaList.find(v => v.id === tId))
			} else if (item.label === 'FEESUBJECT@PROCEDURE') {
				// const id = entity.otherExpenses?[0]?.feeSubjectId
				item.metaList.forEach(v => {
					if (targetFeeTagList.includes(v.tag) && item.metaList.map(o => o.id).includes(tId)) {
						res = Boolean(item.metaList.find(v => v.id === item.feeSubjectId))
					}
				})
			}
		})
		return res
	}
	//获取日期限制
	const renterPeriodTime = () => {
		getRenterPeriodTime(entity?.houseId || '').then(res => {
			let data = res.data
			if (data) {
				entity.minDate = dayjs(data.minDate)
					.subtract(parseInt(data?.rentFreeDay || 0), 'day')
					.format(DATE_FORMAT.DATE)
				entity.maxDate = data.maxDate
			} else {
				entity.minDate = null
				entity.maxDate = null
			}
		})
	}
	// otherExpenses出参只有费用科目id字段 便利判断是否属于押金大类 或 手续费大类
	watchEffect(() => {
		entity.otherExpenses?.forEach(v => {
			if (isFeeSubject(options.feeSubjects, v.feeSubjectId)) {
				v.disabled = true
			}
		})
	})

	const onClickToRemoveRow = (index: any, tableInstance: VxeTableInstance, type?: number) => {
		Modal.confirm({
			title: '系统提示',
			content: '删除后无法恢复，确定删除？',
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			onOk() {
				if (type === 1 && tableInstance.data) {
					tableInstance.data[index - 1].endDate = tableInstance.data[index].endDate
					let dataLastInfo = calculationPeriod(tableInstance.data[index - 1].beginDate, tableInstance.data[index - 1].endDate)
					tableInstance.data[index - 1].year = dataLastInfo?.years
					tableInstance.data[index - 1].month = dataLastInfo?.months
					tableInstance.data[index - 1].day = dataLastInfo?.days
					tableInstance.data[index - 1].betweenMonth = dataLastInfo?.monthNum
				}
				tableInstance.data?.splice(index, 1)
				tableInstance.reloadData(tableInstance.data as [])
			}
		})
	}

	const onDateChange = (dates: string[]) => {
		dates = dates || []
		if (dates[0] != entity.beginTime) {
			entity.freeDays = 0
		}
		entity.beginTime = dates[0]
		entity.endTime = dates[1]

		if ([1].includes(props.contract?.signType)) {
			maxFreeNum.value = dayjs(entity.endTime).diff(dayjs(entity.beginTime), 'day')
		}
	}

	const quickSelectDate = () => {
		// entity.freeDays = 0
		let beginDate = dayjs(entity.beginTime || nowDate())
		let endDate = beginDate.add(entity.leasePeriod || 60, 'month')

		if (beginDate.date() <= endDate.endOf('day').date()) {
			endDate = endDate.subtract(1, 'day')
		}
		entity.beginTime = beginDate.format(DATE_FORMAT.DATE)
		entity.endTime = endDate.format(DATE_FORMAT.DATE)

		form.value?.validate('beginTime')

		if ([1].includes(props.contract?.signType)) {
			maxFreeNum.value = dayjs(entity.endTime).diff(dayjs(entity.beginTime), 'day')
		}
	}

	// 提交合同信息预览账单
	const submit = () => {
		form.value
			?.validate()
			.then(async () => {
				// 部分手动检验
				if (contractDecision.value.frontImgUrl && !entity?.renterInfo?.frontImgUrl) {
					message.warn('请上传证件照片')
					return
				}
				if (contractDecision.value.delivery && !delivery.value) {
					message.warn('请添加物业交割单')
					return
				}

				// 82308字典修改 保存判断选择的字典是否被禁用
				if (props.contractId) {
					// 判断是不是新签
					let typesList: any = []
					let list: any = []
					typesList = await settingApi.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT'], {isUse: 1})
					typesList.data.forEach((e: any) => {
						list.push(...e.metaList)
					})
					list.forEach((e: any) => {
						entity.otherExpenses.forEach((o: any) => {
							if (e.id === o.feeSubjectId) {
								o.active = true
							}
						})
					})
					if (!entity.otherExpenses?.every((e: any) => e?.active == true)) return message.error('选项已禁用，请选择其他选项！')
				}

				visibles.billPreview = true
				if (delivery.value) {
					entity.deliveryAddForm = delivery.value
					entity.deliveryAddForm.contractType = entity.contractType || 1
					entity.deliveryAddForm.deliveryType = 1
				}
			})
			.catch(({errorFields}: any) => {
				form.value?.scrollToField(errorFields[0].name, {
					behavior: 'smooth'
				})
			})
	}

	// 合同签约成功
	const onSubmitSuccess = (value: any) => {
		cancel()
		let timeOut = setTimeout(() => {
			emits('success')
			clearTimeout(timeOut)
		}, 200)
	}
	const cancel = () => {
		house.value = {}
		delivery.value = null
		attachments.value = []
		searchOption.options = []
		maxFreeNum.value = 360
		entity.minDate = null
		entity.maxDate = null
		entity.sublevelContracts = []
		XEUtils.assign(entity, defaultOwnerContract())
		emits('update:visible', false)
	}

	watch(
		() => props.visible,
		(newVal: boolean) => {
			if (newVal) {
				console.log('业主合同签约弹窗')
				init()
			}
		}
	)
</script>
<style lang="less">
	.teleport-footer {
		display: flex;
		justify-content: space-between;
		.ant-select {
			.ant-select-selector {
				border: none;
			}
		}
	}
	.owner-sign-dialog {
		max-width: 1400px;
		.ant-modal-content {
			overflow: hidden;
			.ant-modal-body {
				overflow: auto;
				min-height: 600px;
				max-height: 800px;
			}
		}
	}
</style>
<style lang="less" scoped>
	.free-rang {
		color: #ff4d4f;
		font-size: 12px;
	}
	.rent-free-day {
		text-align: center;
	}
</style>
